package trabajoISW2.data;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import trabajoISW2.domain.implementations.Author;
import trabajoISW2.domain.implementations.Book;

public class AuthorDAO extends BaseDAO implements IAuthorDAO {


	public AuthorDAO(){
		
	}
	public Author createAuthor(Author a){
		getEm().getTransaction().begin();
		getEm().persist(a);
		getEm().getTransaction().commit();
		getEm().close();
		return a;
	}
	
	@Override
	public List<Book> getBookByAuthor(String s){
		Query q1 = getEm().createQuery("Select a FROM Author a WHERE (name LIKE '%"+s+"%') OR (surname LIKE '%"+s+"%')");
		List<Author> authors = q1.getResultList();
		List<Book> books;
		if (authors.isEmpty())
			books = null;
		else {
			books = new LinkedList<Book>();
			Author au;
			Iterator<Author> it = authors.iterator();
			while (it.hasNext()){
				au = it.next();
				books.addAll(au.getBooks());
			}
		}
		return books;
			
	}

	public void deleteAuthor(int id) {
		Author a = getEm().find(Author.class, id);
		if (a != null){
			getEm().getTransaction().begin();
			getEm().remove(a);
			getEm().getTransaction().commit();
			getEm().close();
		}
	}

	public void updateAuthor(Author a) {
		getEm().getTransaction().begin();
		getEm().merge(a);
		getEm().getTransaction().commit();
		getEm().close();

	}

	public List<Author> getAuthors() {

		Query q = getEm().createQuery("Select a FROM Author a");
		return q.getResultList();

	}

	public Author getAuthor(int id) {
		Author a = getEm().find(Author.class, id);
		return a;

	}
}
